package org.high5.datatranslator;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.high5.model.CanvasCoordinates;
import org.high5.model.ConstantsStore;
import org.high5.paintmyworld.MainActivity;
import org.high5.paintmyworld.PrettyLine;

import android.util.Log;
import android.widget.ImageView;

import com.google.android.maps.MapView;

public class LoadingChecker extends Thread {

	private MapView mapView;
	private ImageView iv;
	private MainActivity mainActivity;
	private static Timer myTimer;
	private PrettyLine line;
	int width;
	int height;
	
	public LoadingChecker(MapView mapView,ImageView iv,MainActivity mainActivity,int width,int height) {
		this.mapView = mapView;
		this.iv = iv;
		this.mainActivity = mainActivity;
		this.width = width;
		this.height = height;
		line = new PrettyLine(width, height, iv);
	}
	
	@Override
	public void run() {
		while( mapView.getLatitudeSpan() == 0 || mapView.getLongitudeSpan() == 360000000 ) {
			synchronized(this) {
				try {
					wait(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		List<CanvasCoordinates> canvasCoordinates = DataTranslator.getInstance().getCoordinates(mapView);
		for(CanvasCoordinates canvasCoordinate : canvasCoordinates) {
			Log.i(ConstantsStore.TAG,"x: "+canvasCoordinate.getX()+", y: "+canvasCoordinate.getY());
		}
		try {
			line.redraw(copyToArray(canvasCoordinates));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if( myTimer == null )
        	setTimer();
	}
	
	private void setTimer() {
		myTimer = new Timer();
		myTimer.schedule(new TimerTask() {			
			@Override
			public void run() {
				TimerMethod(mainActivity);
			}
			
		}, 0, 80);
	}
	
	private void TimerMethod(MainActivity mainActivity)
	{
		//This method is called directly by the timer
		//and runs in the same thread as the timer.

		//We call the method that will work with the UI
		//through the runOnUiThread method.
		mainActivity.runOnUiThread(Timer_Tick);
	}


	private Runnable Timer_Tick = new Runnable() {
		public void run() {
		
		//This method runs in the same thread as the UI.    	       
		
		//Do something to the UI thread here
			line.draw();
		}
	};
	
	private CanvasCoordinates[] copyToArray(List<CanvasCoordinates> cc) {
		CanvasCoordinates[] canvasCoordinates = new CanvasCoordinates[cc.size()];
		int i = 0;
		for( CanvasCoordinates c : cc) {
			canvasCoordinates[i] = new CanvasCoordinates(c.getX(),c.getY(),c.getAltitude());
			++i;
		}
		return canvasCoordinates;
	}
	
}
